/*
* ajax请求函数模块
* return 返回值promise对象 异步返回的是response.data 
 */
import axios from 'axios'
export default function ajax(url,data={},type="GET"){
    return new Promise(function(resolve,reject){
        let promise;
        if(type === "GET"){
            //准备url query参数数据
            let dataStr = ''; //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + "&"
            });
            //取出末端的&符号
            if(dataStr !== ''){
                dataStr = dataStr.substring(0,dataStr.lastIndexOf("&"));
                url = url + '?' + dataStr; //url和参数 进行拼接
            }
            //发送get请求
            promise = axios.get(url);
        }else{
            //发送post请求
            promise = axios.post(url,data);
        }
        //执行axios拿出结果
        promise.then(response=>{
            //成功了执行resolve()
            resolve(response.data);
        })
        .catch(error=>{
            //失败了执行reject()
            reject(error);
        })
    })
} 